import type { NextFunction, Response, Request } from "express";
import { getClientIp, getFileSuffix } from "../util/index.js";
import type { DataModel } from "../class/Sql"
import sql from "../sql/index.js"
import AppError from "../class/AppError.js";

// 根据 ip 上传图片
export const uploadImg = (req: Request, res: Response, next: NextFunction) => {
  const obj: DataModel = {
    key: getClientIp(req),
    value: req.saveImg
  }

  sql.write(obj)

  // Mock error
  // setTimeout(() => {
  //   throw new Error("this is a test")
  // }, 2000);
  res.status(200).json({
    status: 'success',
    data: req.saveImg
  })
};

// 获取这个 IP 保存的图片列表
export const getIpSaveImg = (req: Request, res: Response, next: NextFunction) => {
  const ip = getClientIp(req);
  const data = sql.read(ip).filter(filename => getFileSuffix(filename) != "invalid")
  res.status(200).json({
    status: "success",
    data
  })
}

// 获取所有图片数量
export const getSaveNum = (req: Request, res: Response, next: NextFunction) => {
  res.status(200).json({
    status: "success",
    len: sql.getSize()
  })
}

// 获取所有保存的图片数
export const getAllImg = (req: Request, res: Response, next: NextFunction) => {
  const secret = req.body.secret

  if (Number(secret) == 123456) {
    res.status(200).json({
      status: "success",
      data: sql.getAll()
    })
  } else {
    next(new AppError(404, "Invalid request"))
  }
}

// 删除这个 ip 指定的图片
export const deleteImg = (req: Request, res: Response, next: NextFunction) => {
  const name = req.query.name;

  if (!name) return next(new AppError(400, "request error"));
  const ip = getClientIp(req);

  // 修改文件名
  try {
    sql.setInvaildFile(ip, name as string)
    res.status(200).json({
      status: "success"
    })
  } catch (error) {
    return next(new AppError(400, "img not found"));
  }
}
